import type { MenuProps } from "antd"
import { Menu } from "antd"
import React, { useCallback, useContext, useEffect, useMemo, useState } from "react"
import { useLocation, useNavigate } from "react-router"
import { StoreContext } from "@/store"
import * as AntdIcon from "@ant-design/icons"

import { useMobx } from "@whzhuke/mobx"
export const useNavList = () => {
  const { UserStore } = useContext(StoreContext)
  const { pathname } = useLocation()
  const [list, setList] = useState<any[]>([])
  useEffect(() => {
    const current = UserStore.menu?.find(m => m.url?.replace(".html", "") === pathname)
    if (current) {
      const getTree = (item: any, init: any[] = []) => {
        init.push(item!)
        if (item!.parentId > 0) {
          const prev = UserStore.menu?.find(m => m.id === item!.parentId)
          if (prev) {
            return getTree(prev, init)
          }
          return init
        }
        return init
      }
      setList(getTree(current))
    } else {
      setList([])
    }
  }, [pathname])

  return list
}
const LeftMenu = useMobx(() => {
  const { UserStore } = useContext(StoreContext)
  const location = useLocation()
  const nav = useNavigate()
  const navList = useNavList()
  const selectedKeys = useMemo(() => {
    return navList.map(n => n.id.toString())
  }, [navList])

  const [openKeys, setOpenKeys] = useState<string[]>(selectedKeys.slice(-1))
  const onOpenChange = useCallback<Required<MenuProps>["onOpenChange"]>(
    keys => {
      openKeys.toString() !==
        keys
          .slice(-1)
          .map(m => m)
          .toString() && setOpenKeys(keys.slice(-1).map(m => m))
    },
    [openKeys]
  )

  const toLink = useCallback(
    (item: any) => () => {
      if (item?.url) {
        nav(item.url)
      }
    },
    []
  )
  const items = useMemo((): MenuProps["items"] => {
    const renderMenu = (list: typeof UserStore.MenuTreeNode = []): MenuProps["items"] => {
      return list.map((item: any) => {
        return {
          label: item.name,
          icon: item.icon ? React.createElement(AntdIcon[item.icon]) : undefined,
          key: item.id,
          title: item.name,
          onClick: toLink(item),
          children: item.children?.length ? renderMenu(item.children) : undefined
        }
      })
    }

    return renderMenu(UserStore.MenuTreeNode)
  }, [UserStore.MenuTreeNode])

  useEffect(() => {
    setOpenKeys(selectedKeys.slice(1))
  }, [selectedKeys])

  return <Menu theme="dark" onOpenChange={onOpenChange} selectedKeys={selectedKeys} openKeys={openKeys} mode="inline" items={items} />
})
export default LeftMenu
